package com.application.admin;

import com.application.common.Constant;
import com.application.common.utils.VerifyKit;
import com.application.model.Global;
import com.application.module.usermoney.ChargeUserMoney;
import com.application.validate.SuperAdminValidator;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;
import com.platform.mvc.user.User;
import com.platform.mvc.user.UserValidator;
import com.platform.tools.ToolCache;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 菜单管理
 * @author 董华健
 */
@Controller("/admin/user")
public class UserController extends BaseController {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(UserController.class);

    /**
	 * 菜单管理首页
	 */
	public void index() {

        splitPage.setOrderColunm("create_at");
        splitPage.setOrderMode("desc");
        paging(splitPage, User.sqlId_splitPageSelect, User.sqlId_splitPageFrom);

        renderOk(splitPage);
	}


    /**
     * 保存新增用户
     */
    @Before({UserValidator.class})
    public void save() {

        String password = getPara("password");
        User user = User.dao.getModelByMap(password, super.getParamMap());
        try {
            //特殊数据类型处理
            User.saveInfo(user);
        } catch (Exception e) {
            e.printStackTrace();
            renderErr(500, "", e.getMessage());
            return;
        }

        renderOk("reload", "保存成功", null);
    }


    /**
     * 更新,修改管理员信息时需校验身份
     */
    public void update() {
        String password = getPara("password");

        User user = User.dao.getModelByMap(password, super.getParamMap());

        if (Constant.group_SuperAdmin.equalsIgnoreCase(user.getRoleId())
                && !Constant.group_SuperAdmin.equalsIgnoreCase(super.getCUser().getRoleId())) {
            renderErr(400, "", "权限验证失败");
            return;
        }

        boolean f = User.dao.updateAlternative(user);

        if(f){
            renderOk("refresh", "修改成功", null);
        } else {
            renderErr(500, "", "修改失败");
        }

    }

    /**
     * 删除
     */
    @Before(SuperAdminValidator.class)
    public void delete() {
        User.dao.deleteByIds(getPara() == null ? getPara("id") : getPara());
        renderOk("refresh", "删除成功", null);
    }

    /*
    查询用户信息
     */
    public void view(){
        String userid = getPara() == null ? super.getCUserIds() : getPara();
        User user = User.dao.cacheGetByUserId(userid);
        user.setPassword("");
        if(user.get("referee_userid") != null) {
            User p = User.dao.findById(user.getInt("referee_userid"));
            if(p != null) {
                user.put("referee_name", p.getName() + "(" + p.getUsername() + ")");
            }
        }
        renderOk(user);
    }

    /*
    给用户充值
     */
    public void charge(){
        String msg = "充值成功";
        String uid = getPara("id");
        String money = getPara("money");
        String code = getPara("valicode");
        Global g = Global.cacheGetByCode(Global.Code.admin_mobile);

        if (VerifyKit.verify(g.getValue(), code)) {
            //金额校验
            String m = ToolCache.get(g.getValue() + "_extra");
            if(money.equalsIgnoreCase(m)){
                User u = User.dao.findById(uid);
                u.set("money", u.getBigDecimal("money").add(new BigDecimal(money))).update();
                User.dao.cacheRemove(uid);
                String orderNo = "c" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "0000";
                new ChargeUserMoney().create(u.getId(), m, orderNo, super.getCUserId());
                renderOk("", msg, null);
                return;
            } else {
                msg = "充值金额已改变，请重新输入";
                renderErr(400, "", msg);
                return;
            }
        }
        renderErr(400, "", "充值失败");
    }


    /**
     * 修改用户角色
     * @param id
     * @param roleId
     */
    @Before(SuperAdminValidator.class)
    public void changeRole(){
        String rid = getPara("role_id");
        String uid = getPara("id");
        Date date = null;

        /*if(StrKit.notBlank(getPara("role_date"))) {
            date = java.sql.Date.valueOf(getPara("role_date"));
        }*/
        if(StrKit.notBlank(getPara("role_date"))) {
            date = getParaToDate("role_date");
        }

        if(StrKit.isBlank(rid) || StrKit.isBlank(uid)){
            renderErr(400, "", "参数为空");
            return;
        }
        int i = Db.update("update pt_user set role_id = ? ,role_date = ? where id =? ", rid, date, uid);

        if(i > 0) {
            User.dao.cacheRemove(uid);
            renderOk("refresh", "修改成功", null);
        } else {
            renderErr(400, "", "修改失败");
        }
    }

    /*
    参数:keyword
     */
    public void query(){
        List<User> list = User.dao.queryByNo(getPara("keyword"));
        success(list);
    }
}


